package com.sean.community.comtroller.interceptor;

import com.sean.community.entity.User;
import com.sean.community.service.DataStatisticsService;
import com.sean.community.util.HostHolder;
import com.sean.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DataStatisticsInterceptor implements HandlerInterceptor {
    private DataStatisticsService dataStatisticsService;
    private HostHolder hostHolder;

    @Autowired
    public void setDataStatisticsService(DataStatisticsService dataStatisticsService) {
        this.dataStatisticsService = dataStatisticsService;
    }

    @Autowired
    public void setHostHolder(HostHolder hostHolder) {
        this.hostHolder = hostHolder;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 统计 UV
        String ip = request.getRemoteHost();
        dataStatisticsService.recodeUV(ip);
        // 统计 DAU
        User user = hostHolder.getUser();
        if(user != null){
            dataStatisticsService.recodeDAU(user.getId());
        }
        return true;
    }
}
